import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:share_fit/app/controllers/device/permission/permission_const.dart';
import 'package:share_fit/app/controllers/space/space_const.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/helper/storage_mixin.dart';
import 'package:share_fit/app/tools/app_util.dart';
import 'package:share_fit/app/tools/color_const.dart';
import 'package:share_fit/app/tools/log_utils.dart';
import 'package:share_fit/app/ute/uteped_const.dart';
import 'package:share_fit/app/ute/uteped_helper.dart';
import 'package:share_fit/app/ute/uteped_mixin.dart';
import 'package:share_fit/generated/locales.g.dart';

abstract class BaseController extends FullLifeCycleController
    with UTEPedMixin,FullLifeCycleMixin, StorageMixin, GetTickerProviderStateMixin
    implements UTEPedListener {
  /// 封装了一些与原生通信相关的逻辑 `BaseController`

  late AnimationController animCtrl;

  SnackbarController? snackbarController;
  SnackbarStatus? snackbarStatus;

  @override
  void onInit() {
    super.onInit();
    animCtrl = AnimationController(vsync: this, duration: Duration(seconds: getAnimDuration()));
    initStorage();
    UTEPedHelper.addListener(this);
    initState();
  }

  @override
  void dispose() {
    logger.d("$this dispose");
    super.dispose();
  }

  @override
  void onClose() {
    logger.d("$this onClose");
    removeStorageListeners();
    UTEPedHelper.removeListener(this);
    super.onClose();
  }

  @override
  void onReady() {
    logger.d("$this onReady");
    super.onReady();
  }

  /// 下方这些均是app前后台切换相关，并不是flutter页面状态变化
  @override
  void onResumed() {
    logger.d("$this resume");
  }

  @override
  void onPaused() {
    logger.d("$this pause");
  }

  @override
  void onDetached() {
    logger.d("$this detached");
  }

  @override
  void onHidden() {
    logger.d("$this hide");
  }

  @override
  void onInactive() {
    logger.d("$this inactive");
  }

  int getAnimDuration() {
    return 300;
  }

  void delayed(callback, {milliseconds = 1}) {
    Future.delayed(Duration(milliseconds: milliseconds), callback);
  }

  String getAddress() {
    return read(UTEPedConst.keyAddress, defaultValue: '', global: true);
  }

  void showLoading() {
    cancelLoading();
    Get.dialog(
      Center(
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
          width: 700.w,
          height: 360.w,
          child: Center(
            child: CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(ColorConst.accentColor),
            ),
          ),
        ),
      ),
      barrierDismissible: Platform.isIOS,
    );
  }

  void showTips(title, message) {
    AppUtil.showTips(title, message);
  }

  Future<void> cancelLoading() async {
    if (Get.isSnackbarOpen) {
      // await Get.closeCurrentSnackbar();
      Get.closeCurrentSnackbar();
      await Future.delayed(const Duration(milliseconds: 200));
    }
    if (Get.isDialogOpen == true) {
      Get.back();
    }
  }

  void showInfoDialog(String title, {autoDismiss = true, dismissSecs=2, callback}) {
    if (Get.overlayContext != null) {
      var dlg = showDialog(
          context: Get.overlayContext!,
          barrierDismissible: Platform.isIOS,
          builder: (dlgContext) {
            return Material(
              type: MaterialType.transparency,
              child: Center(
                child: SizedBox(
                  width: 916.w,
                  height: 736.w,
                  child: Container(
                    decoration: const ShapeDecoration(
                      color: Color(0xffffffff),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(
                          Radius.circular(20.0),
                        ),
                      ),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Image.asset(
                            'assets/images/device/device_dialog_success.png',
                            width: 222.w,
                            height: 222.h),
                        SizedBox(height: 34.h),
                        Text(title, style: TextStyle(fontSize: 54.sp)),
                        SizedBox(height: 60.h),
                      ],
                    ),
                  ),
                ),
              ),
            );
          });

      if (autoDismiss) {
        Future.delayed(Duration(seconds: dismissSecs), ()=>{
          if (Get.overlayContext != null) {
            Navigator.pop(Get.overlayContext!)
          },
          if (callback != null) {
            callback()
          }
        });
      }
    }
  }

  void showPermissionDialog(message, {callback}) {
    Get.defaultDialog(
        title: LocaleKeys.info.ts,
        textConfirm: LocaleKeys.setting.ts,
        textCancel: LocaleKeys.cancel.ts,
        buttonColor: ColorConst.accentColor,
        middleText: message,
        barrierDismissible: Platform.isIOS,
        onCancel: () => {},
        onConfirm: () => {
          Get.back(),
          if (callback == null) {
            vRemoteReqAsync(PermissionConst.methodToPermissionPage, {})
          }
          else {
            callback()
          }
        }
    );
  }

  /// 读取一些需要原生通信参数
  void initState();

}